package com.cnap.db.handler;

import cn.hutool.core.util.StrUtil;
import com.cnap.model.schedule.engine.alg.CreateVmInfo;
import com.cnap.utils.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * cluserInfos handler
 *
 * @author xc
 **/
public class VmInfoHandler implements TypeHandler<List<CreateVmInfo>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<CreateVmInfo> clusterInfos, JdbcType jdbcType) throws SQLException {
        String str = JsonUtil.objectToJsonStr(clusterInfos);
        preparedStatement.setString(i, str);
    }

    @Override
    public List<CreateVmInfo> getResult(ResultSet resultSet, String s) throws SQLException {
        String jsonStr = resultSet.getString(s);
        if (StrUtil.isEmpty(jsonStr)) {
            return null;
        }
        return JsonUtil.jsonStrToObject(jsonStr, new TypeReference<List<CreateVmInfo>>() {
        });
    }

    @Override
    public List<CreateVmInfo> getResult(ResultSet resultSet, int i) throws SQLException {
        String jsonStr = resultSet.getString(i);
        if (StrUtil.isEmpty(jsonStr)) {
            return null;
        }
        return JsonUtil.jsonStrToObject(jsonStr, new TypeReference<List<CreateVmInfo>>() {
        });
    }

    @Override
    public List<CreateVmInfo> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String jsonStr = callableStatement.getString(i);
        if (StrUtil.isEmpty(jsonStr)) {
            return null;
        }
        return JsonUtil.jsonStrToObject(jsonStr, new TypeReference<List<CreateVmInfo>>() {
        });
    }
}
